package com.jinzhi.jzweb.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzweb.domain.CoursesDO;
import com.jinzhi.jzweb.domain.CoustuQuestionsAnswersDO;
import com.jinzhi.jzweb.service.CoursesService;
import com.jinzhi.jzweb.service.CoustuQuestionsAnswersService;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <pre>
 * 学生课程问答信息表
 * </pre>
 * <small> 2020-07-01 17:59:38 | lance</small>
 */
@Controller
@RequestMapping("/jzweb/coustuQuestionsAnswers")
public class CoustuQuestionsAnswersController extends BaseController {
    @Autowired
    private CoustuQuestionsAnswersService coustuQuestionsAnswersService;
	@Autowired
	private CoursesService coursesService;
	@Autowired
	private UserService userService;

    @GetMapping()
    @RequiresPermissions("jzweb:coustuQuestionsAnswers:coustuQuestionsAnswers")
    String CoustuQuestionsAnswers() {
        return "jzweb/coustuQuestionsAnswers/coustuQuestionsAnswers";
    }

    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("jzweb:coustuQuestionsAnswers:coustuQuestionsAnswers")
    public Result<Page<CoustuQuestionsAnswersDO>> list(HttpServletRequest req, CoustuQuestionsAnswersDO coustuQuestionsAnswersDTO) {
		Wrapper<CoustuQuestionsAnswersDO> wrapper = new EntityWrapper<CoustuQuestionsAnswersDO>().orderBy("id", false);
        if (coustuQuestionsAnswersDTO.getState() != null){
            wrapper.eq("state",coustuQuestionsAnswersDTO.getState());
        }
		String strr = roleCourse(req,coustuQuestionsAnswersDTO.getCoursesName());
		if (StringUtils.isBlank(strr)) {
			wrapper.and();
			wrapper.eq("courses_id", null);
		} else if(!strr.equals("@#$%^&*!~")){
			wrapper.and();
			wrapper.in("courses_id", strr.substring(0, strr.length() - 1));
		}
		if (org.apache.commons.lang3.StringUtils.isNotBlank(coustuQuestionsAnswersDTO.getUserName())){
			Wrapper<UserDO> cerWrapper = new EntityWrapper<UserDO>().like("name",coustuQuestionsAnswersDTO.getUserName());
			List<UserDO>  userDOS = userService.selectList(cerWrapper);
			String str = "";
			for (UserDO userDO : userDOS){
				str = str + userDO.getId() + ",";
			}
			wrapper.and();
			if(org.apache.commons.lang3.StringUtils.isNotBlank(str)){
				wrapper.in("user_id",str.substring(0,str.length()-1));
			}else{
				wrapper.eq("user_id",null);
			}
		}
		wrapper.eq("pid",0);//只查询出所有的父级，即初始页面只展示所有问题！
		Page<CoustuQuestionsAnswersDO> page = coustuQuestionsAnswersService.selectPage(getPage(CoustuQuestionsAnswersDO.class), wrapper);
		List list = new ArrayList();
		for (int i = 0; i < page.getRecords().size(); i++) {
			CoustuQuestionsAnswersDO obj = (CoustuQuestionsAnswersDO) page.getRecords().get(i);
			if (obj.getUserId() != null){
				UserDO userDO = userService.selectById(obj.getUserId());
				if (userDO != null) {
					obj.setUserName(userDO.getName());
				}
			}
			if (obj.getCoursesId() != null){
				CoursesDO coursesDO = coursesService.selectById(obj.getCoursesId());
				if (coursesDO != null) {
					obj.setCoursesName(coursesDO.getName());
				}
			}
			list.add(obj);
		}
        page.setRecords(list);
        return Result.ok(page);
    }

    @GetMapping("/add/{id}")
    @RequiresPermissions("jzweb:coustuQuestionsAnswers:add")
    String add(@PathVariable("id") Long id, Model model) {
        model.addAttribute("pid",id);//问题id
        CoustuQuestionsAnswersDO coustuQuestionsAnswers = coustuQuestionsAnswersService.selectById(id);
        model.addAttribute("coursesId",coustuQuestionsAnswers.getCoursesId());//课程id
        model.addAttribute("questions",coustuQuestionsAnswers.getContents());//问题
        model.addAttribute("state",coustuQuestionsAnswers.getState());//状态（0未回答，1已回答）
        if(coustuQuestionsAnswers.getState().equals(1)){
            CoustuQuestionsAnswersDO coustuQuestionsAnswersDO = coustuQuestionsAnswersService.findOneByKv("pid",id);
            if(coustuQuestionsAnswersDO != null){
                model.addAttribute("id",coustuQuestionsAnswersDO.getId());//回答id
                model.addAttribute("answers",coustuQuestionsAnswersDO.getContents());//回答
            }
        }
        return "jzweb/coustuQuestionsAnswers/add";
    }

    @Log("培训机构或讲师添加回复")
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("jzweb:coustuQuestionsAnswers:add")
    public Result<String> save(CoustuQuestionsAnswersDO coustuQuestionsAnswers) {
        CoustuQuestionsAnswersDO coustuQuestionsAnswersDO = coustuQuestionsAnswersService.findOneByKv("pid",coustuQuestionsAnswers.getPid());
        if(coustuQuestionsAnswersDO == null){
            coustuQuestionsAnswers.setUserId(this.getUserId());
            coustuQuestionsAnswers.setState(1);//默认已回答
            boolean cc = coustuQuestionsAnswersService.insert(coustuQuestionsAnswers);
            if(cc){
                CoustuQuestionsAnswersDO coustuQuestionsAnswersDO1= coustuQuestionsAnswersService.selectById(coustuQuestionsAnswers.getPid());
                coustuQuestionsAnswersDO1.setState(1);//问题状态改为已回答
                boolean dd = coustuQuestionsAnswersService.updateById(coustuQuestionsAnswersDO1);
                return dd ? Result.ok() : Result.fail();
            }else{
                return Result.fail();
            }
        }else{
            return Result.fail("已回复，请勿重复！");
        }
    }

    @Log("培训机构或讲师删除自己的回复")
    @PostMapping("/removeAnswers")
    @ResponseBody
    @RequiresPermissions("jzweb:coustuQuestionsAnswers:remove")
    public Result<String> removeAnswers(Long id) {
        CoustuQuestionsAnswersDO coustuQuestionsAnswers = coustuQuestionsAnswersService.selectById(id);
        if(coustuQuestionsAnswers.getUserId().equals(this.getUserId())){
            boolean dd = coustuQuestionsAnswersService.deleteById(id);
               if(dd){
                    CoustuQuestionsAnswersDO coustuQuestionsAnswersDO1= coustuQuestionsAnswersService.selectById(coustuQuestionsAnswers.getPid());
                    coustuQuestionsAnswersDO1.setState(0);//问题状态改为未回答
                    boolean cc = coustuQuestionsAnswersService.updateById(coustuQuestionsAnswersDO1);
                    return cc ? Result.ok() : Result.fail();
                }else{
                     return Result.fail();
                }
        }else{
            return Result.fail();
        }
    }

    @GetMapping("/edit/{id}")
    @RequiresPermissions("jzweb:coustuQuestionsAnswers:edit")
    String edit(@PathVariable("id") Long id, Model model) {
        CoustuQuestionsAnswersDO coustuQuestionsAnswers = coustuQuestionsAnswersService.selectById(id);
        model.addAttribute("coustuQuestionsAnswers", coustuQuestionsAnswers);
        return "jzweb/coustuQuestionsAnswers/edit";
    }

    @Log("修改学生课程问答信息表")
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("jzweb:coustuQuestionsAnswers:edit")
    public Result<String> update(CoustuQuestionsAnswersDO coustuQuestionsAnswers) {
        boolean update = coustuQuestionsAnswersService.updateById(coustuQuestionsAnswers);
        return update ? Result.ok() : Result.fail();
    }

    @Log("删除学生课程问答信息表")
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("jzweb:coustuQuestionsAnswers:remove")
    public Result<String> remove(Long id) {
        coustuQuestionsAnswersService.deleteById(id);
        return Result.ok();
    }

    @Log("批量删除学生课程问答信息表")
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("jzweb:coustuQuestionsAnswers:batchRemove")
    public Result<String> remove(@RequestParam("ids[]") Long[] ids) {
        coustuQuestionsAnswersService.deleteBatchIds(Arrays.asList(ids));
        return Result.ok();
    }

}
